//
//  WLLRefreshControl.swift
//  09下拉刷新
//
//  Created by 王乐乐 on 16/8/15.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
//MARK: - 刷新控件的状态
enum WLLRefreshControlState : Int {
    //正常
    case Normal = 0
    //下拉中
    case Pulling = 1
    //刷新中
    case Referesh = 2
    
}


//MARK: - 全局的参数
/// 屏幕宽
let KScreenW = UIScreen.mainScreen().bounds.width
/// 自定义控件高
let  WLLRefreshControlH :CGFloat = 50


class WLLRefreshControl: UIControl {
    //记录滑动视图
    var scrollView : UIScrollView?
    //记录状态
    var WLLstate : WLLRefreshControlState  = .Normal{
        
        didSet{
            
            switch WLLstate {
            //正常
            case .Normal:
                messageLabel.text = "正常"
                UIView.animateWithDuration(0.25, animations: {
                    //恢复原位
                    self.pullImageView.transform = CGAffineTransformIdentity
                })
                
                // 只有上个状态为刷新中 才减去scrollView 顶部滑动的距离
                if oldValue == .Referesh {
                    UIView.animateWithDuration(0.25, animations: {
                        self.scrollView?.contentInset.top -= WLLRefreshControlH
                        
                        }, completion: { (_) in
                            //结束动画
                            self.activityView.stopAnimating()
                            self.pullImageView.hidden = false
                    })
                }
                
                
                
            // 下拉
            case .Pulling:
                
                messageLabel.text = "下拉"
                UIView.animateWithDuration(0.25, animations: {
                    self.pullImageView.transform = CGAffineTransformMakeRotation(CGFloat( M_PI*3))
                })
                
            //刷新
            case .Referesh:
                messageLabel.text = "刷新中"
                UIView.animateWithDuration(0.25, animations: {
                    // 只有当前状态为刷新中 才加上scrollView 顶部滑动的距离
                    self.scrollView?.contentInset.top += WLLRefreshControlH
                    }, completion: { (_) in
                        self.pullImageView.hidden = true
                        self.activityView.startAnimating()
                        //MARK: - 告知外界刷新
                        self.sendActionsForControlEvents(UIControlEvents.ValueChanged)
                })
                
                
                
            }
            
        }
    }
    
    
    /**
     供外界调用,结束动画
     */
    func endRefreshing()  {
        WLLstate = .Normal
    }
    
    
    
    
    //该控件要加到谁身上
    override func willMoveToSuperview(newSuperview: UIView?) {
        print(newSuperview)
        
        guard let scrollView = newSuperview as? UIScrollView else{
            return
        }
        //赋值
        self.scrollView  = scrollView
        //添加观察者
        scrollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
        
    }
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        //记录 scrollView的滚动  强解包
        let contentOffsetY = self.scrollView!.contentOffset.y
//        print(contentOffsetY)
        //顶部滑动的距离
        let contentInsetTop = self.scrollView!.contentInset.top
        //        print(contentInsetTop)
        if scrollView!.dragging {//拖动中
            
            
            if contentOffsetY > -contentInsetTop-WLLRefreshControlH && WLLstate == .Pulling {
                print("正常")
                WLLstate = .Normal
                
            } else if contentOffsetY <= -contentInsetTop-WLLRefreshControlH && WLLstate == .Normal{
                print("下拉中")
                WLLstate = .Pulling
                
            }
            
        }else{ //松手了
            if WLLstate == .Pulling{
                print("刷新中")
                WLLstate = .Referesh
            }
            
            
        }
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: CGRect(x: 0, y: -WLLRefreshControlH , width: KScreenW, height: WLLRefreshControlH))
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //MARK: - 设置视图
    func setupUI ()  {
        backgroundColor = UIColor.orangeColor()
        //添加控件
        addSubview(messageLabel)
        addSubview(activityView)
        addSubview(pullImageView)
        //添加约束
        
        // 提示信息文字
        //取消translatesAutoresizingMaskIntoConstraints
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0))
        //菊花
        activityView.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: activityView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: -35))
        
        addConstraint(NSLayoutConstraint(item: activityView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
        //下拉箭头
        pullImageView.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: pullImageView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: pullImageView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: -35))
        
    }
    
    
    
    
    //MARK: - 懒加载控件
    /// 提示信息文字
    private lazy var messageLabel : UILabel = {
        let lab = UILabel ()
        lab.text = "正常"
        lab.textColor = UIColor.whiteColor()
        lab.font = UIFont.systemFontOfSize(15)
        return lab
    }()
    /// 菊花
    private lazy var activityView : UIActivityIndicatorView = UIActivityIndicatorView()
    /// 下拉箭头
    private lazy var pullImageView : UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    
    
}















